<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>菜单管理系统</title>
    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .error {
            color: red;
            margin: 10px 0;
        }
        .success {
            color: green;
            margin: 10px 0;
        }
        button {
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
        }
        .nav {
            margin-bottom: 20px;
        }
        .nav a {
            margin-right: 10px;
            text-decoration: none;
            color: #333;
        }
        .section {
            margin-bottom: 40px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="nav">
            <a href="index.html">用户管理</a>
            <a href="role.html">角色管理</a>
            <a href="menu.html">菜单管理</a>
        </div>
        
        <div id="errorMessage" class="error"></div>
        <div id="successMessage" class="success"></div>
        
        <div class="section">
            <h2>添加菜单</h2>
            <form id="menuForm">
                <div class="form-group">
                    <label for="menuName">菜单名称：</label>
                    <input type="text" id="menuName" required>
                </div>
                <div class="form-group">
                    <label for="menuPath">菜单路径：</label>
                    <input type="text" id="menuPath" required>
                </div>
                <div class="form-group">
                    <label for="menuIcon">菜单图标：</label>
                    <input type="text" id="menuIcon" placeholder="可选">
                </div>
                <div class="form-group">
                    <label for="parentId">父菜单 ID：</label>
                    <input type="number" id="parentId" placeholder="可选">
                </div>
                <button type="submit">添加菜单</button>
            </form>
        </div>

        <div class="section" id="editMenuSection" style="display: none;">
            <h2>编辑菜单</h2>
            <form id="editMenuForm">
                <input type="hidden" id="editMenuId">
                <div class="form-group">
                    <label for="editMenuName">菜单名称：</label>
                    <input type="text" id="editMenuName" required>
                </div>
                <div class="form-group">
                    <label for="editMenuPath">菜单路径：</label>
                    <input type="text" id="editMenuPath" required>
                </div>
                <div class="form-group">
                    <label for="editMenuIcon">菜单图标：</label>
                    <input type="text" id="editMenuIcon" placeholder="可选">
                </div>
                <div class="form-group">
                    <label for="editParentId">父菜单 ID：</label>
                    <input type="number" id="editParentId" placeholder="可选">
                </div>
                <button type="submit">更新菜单</button>
                <button type="button" id="cancelEditButton">取消</button>
            </form>
        </div>

        <div class="section">
            <h3>菜单列表</h3>
            <table id="menuTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>菜单名称</th>
                        <th>路径</th>
                        <th>图标</th>
                        <th>父菜单 ID</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <script>
        const API_URL = 'http://localhost:3000';
        const errorMessageElement = document.getElementById('errorMessage');
        const successMessageElement = document.getElementById('successMessage');

        function showMessage(message, isError = false) {
            const element = isError ? errorMessageElement : successMessageElement;
            element.textContent = message;
            setTimeout(() => {
                element.textContent = '';
            }, 3000);
        }

        // 获取所有菜单
        async function fetchMenus() {
            try {
                const response = await fetch(`${API_URL}/menus`);
                if (!response.ok) {
                    throw new Error('获取菜单列表失败');
                }
                const menus = await response.json();
                
                const tbody = document.querySelector('#menuTable tbody');
                tbody.innerHTML = '';
                menus.forEach(menu => {
                    tbody.innerHTML += `
                        <tr>
                            <td>${menu.id}</td>
                            <td>${menu.name}</td>
                            <td>${menu.path}</td>
                            <td>${menu.icon || '无'}</td>
                            <td>${menu.parent ? menu.parent.id : '无'}</td>
                            <td>
                                <button onclick="editMenu('${menu.id}')">编辑</button>
                                <button onclick="deleteMenu('${menu.id}')">删除</button>
                            </td>
                        </tr>
                    `;
                    // 如果有子菜单，显示子菜单
                    if (menu.children && menu.children.length > 0) {
                        menu.children.forEach(child => {
                            tbody.innerHTML += `
                                <tr>
                                    <td>${child.id}</td>
                                    <td>-- ${child.name}</td>
                                    <td>${child.path}</td>
                                    <td>${child.icon || '无'}</td>
                                    <td>${child.parent ? child.parent.id : '无'}</td>
                                    <td>
                                        <button onclick="editMenu('${child.id}')">编辑</button>
                                        <button onclick="deleteMenu('${child.id}')">删除</button>
                                    </td>
                                </tr>
                            `;
                        });
                    }
                });
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 添加菜单
        document.getElementById('menuForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const menuData = {
                    name: document.getElementById('menuName').value,
                    path: document.getElementById('menuPath').value,
                    icon: document.getElementById('menuIcon').value,
                    parentId: parseInt(document.getElementById('parentId').value) || null
                };

                const response = await fetch(`${API_URL}/menus`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(menuData)
                });

                if (!response.ok) {
                    throw new Error('添加菜单失败');
                }

                document.getElementById('menuForm').reset();
                showMessage('菜单添加成功！');
                fetchMenus();
            } catch (error) {
                showMessage(error.message, true);
            }
        });

        // 编辑菜单
        async function editMenu(id) {
            try {
                const response = await fetch(`${API_URL}/menus/${id}`);
                if (!response.ok) {
                    throw new Error('获取菜单信息失败');
                }
                const menu = await response.json();
                
                // 填充编辑表单
                document.getElementById('editMenuId').value = menu.id;
                document.getElementById('editMenuName').value = menu.name;
                document.getElementById('editMenuPath').value = menu.path;
                document.getElementById('editMenuIcon').value = menu.icon || '';
                document.getElementById('editParentId').value = menu.parent ? menu.parent.id : '';

                // 显示编辑表单
                document.getElementById('editMenuSection').style.display = 'block';
            } catch (error) {
                showMessage(error.message, true);
            }
        }

        // 更新菜单
        document.getElementById('editMenuForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const id = document.getElementById('editMenuId').value;
            const updatedMenuData = {
                name: document.getElementById('editMenuName').value,
                path: document.getElementById('editMenuPath').value,
                icon: document.getElementById('editMenuIcon').value,
                parentId: document.getElementById('editParentId').value ? 
                    parseInt(document.getElementById('editParentId').value) : null
            };

            try {
                const response = await fetch(`${API_URL}/menus/${id}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(updatedMenuData)
                });

                if (!response.ok) {
                    throw new Error('更新菜单失败');
                }

                showMessage('菜单更新成功！');
                fetchMenus();
                document.getElementById('editMenuSection').style.display = 'none';
            } catch (error) {
                showMessage(error.message, true);
            }
        });

        // 取消编辑
        document.getElementById('cancelEditButton').addEventListener('click', () => {
            document.getElementById('editMenuSection').style.display = 'none';
        });

        // 删除菜单
        async function deleteMenu(id) {
            if (confirm('确定要删除这个菜单吗？')) {
                try {
                    const response = await fetch(`${API_URL}/menus/${id}`, {
                        method: 'DELETE'
                    });

                    if (!response.ok) {
                        throw new Error('删除菜单失败');
                    }

                    showMessage('菜单删除成功！');
                    fetchMenus();
                } catch (error) {
                    showMessage(error.message, true);
                }
            }
        }

        // 初始化
        fetchMenus();
    </script>
</body>
</html> 